package com.mentalhealthplatform;

import com.mentalhealthplatform.utils.decryptUtils.property.AESUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EncryptPropertiesFile {

    // 解密密钥
    private static final String SECRET_KEY = "yourSecretKey";  // 替换为您的实际密钥

    // 用于匹配包含敏感信息的行，如 password、url、key
    private static final List<String> SENSITIVE_KEYS = Arrays.asList("password", "url", "key","endpoint","uri");

    // 用于标识加密值的前缀
    private static final String ENCRYPTED_PREFIX = "ENC_";

    public static void main(String[] args) throws Exception {
        // 读取 application.properties 文件
        File file = new File("src/main/resources/application.properties");
        List<String> lines = readPropertiesFile(file);

        // 加密敏感信息
        List<String> encryptedLines = new ArrayList<>();
        for (String line : lines) {
            encryptedLines.add(processLine(line));
        }

        // 将加密后的内容写回到文件
        writeToFile(file, encryptedLines);

        System.out.println("Sensitive information has been encrypted.");
    }

    // 读取 properties 文件
    private static List<String> readPropertiesFile(File file) throws IOException {
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        }
        return lines;
    }

    // 处理每一行，检查是否需要加密
    private static String processLine(String line) {
        // 检查行是否包含敏感字段
        for (String sensitiveKey : SENSITIVE_KEYS) {
            if (line.toLowerCase().contains(sensitiveKey)) {
                // 提取键值对
                String[] parts = line.split("=");
                if (parts.length == 2) {
                    String key = parts[0].trim();
                    String value = parts[1].trim();

                    // 检查值是否已经加密，如果是，则不进行加密
                    if (value.startsWith(ENCRYPTED_PREFIX)) {
                        return line;  // 如果已经加密，直接返回原行
                    }

                    try {
                        // 对敏感信息进行加密
                        String encryptedValue = AESUtils.encrypt(value, SECRET_KEY);
                        return key + "=" + ENCRYPTED_PREFIX + encryptedValue;  // 加密后添加 ENC_ 前缀
                    } catch (Exception e) {
                        e.printStackTrace();
                        return line;  // 如果加密失败，返回原始行
                    }
                }
            }
        }
        return line;  // 返回原始行
    }

    // 将加密后的内容写回文件
    private static void writeToFile(File file, List<String> lines) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        }
    }
}
